package com.caius.xiaohashu.oss.biz.strategy.Impl;

import com.aliyun.oss.OSS;
import com.caius.xiaohashu.oss.biz.config.AliyunOSSProperties;
import com.caius.xiaohashu.oss.biz.strategy.FileStrategy;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.util.UUID;

/**
 * @author Caius
 * @description
 * @since Created in 2025-05-16
 */
@Slf4j
public class AliyunOSSFileStrategy implements FileStrategy {

    @Resource
    private AliyunOSSProperties aliyunOSSProperties;

    @Resource
    private OSS aliyunOSSClient;

    @Override
    @SneakyThrows
    public String uploadFile(MultipartFile file, String buketName) {
        log.info("## 文件上传至阿里云 OSS ...");
        if (file == null || file.getSize() == 0) {
            log.error("==> 上传文件异常： 文件大小不能为空 ...");
            throw new RuntimeException("文件大小不能为空");
        }
        String originalFilename = file.getOriginalFilename();
        String contentType = file.getContentType();

        String key = UUID.randomUUID().toString().replace("-", "");
        String suffex = originalFilename.substring(originalFilename.lastIndexOf("."));

        String objectName = String.format("%s%s", key, suffex);

        log.info("==> 开始上传文件至 aliyun, ObjectName: {}", objectName);

        // 上传文件到 aliyun
        aliyunOSSClient.putObject(buketName, objectName, new ByteArrayInputStream(file.getInputStream().readAllBytes()));

        String url = String.format("https://%s.%s/%s", buketName, aliyunOSSProperties.getEndPoint(), objectName);

        log.info("==> 上传文件至阿里云成功， 访问路径：{}", url);

        return url;
    }
}
